#include "mathHandler.h"
#include "cpuSimulator.h"
#include <QDebug>
#include <cmath>

/**
 * @brief MathHandler构造函数
 * @param parent 父对象指针
 */
MathHandler::MathHandler(QObject *parent)
    : SystemCallHandler(parent)
    , randomGenerator(QRandomGenerator::global())
{
    // 初始化数学常数表
    constantsTable["PI"] = PI;
    constantsTable["E"] = E;
}

/**
 * @brief MathHandler析构函数
 */
MathHandler::~MathHandler()
{
    // Qt对象会自动清理
}

/**
 * @brief 处理中断
 * @param interruptNumber 中断号
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleInterrupt(int interruptNumber, CpuSimulator* cpu)
{
    if (!isInterruptSupported(interruptNumber)) {
        return createErrorResult(-1, "不支持的数学运算中断号");
    }
    
    switch (interruptNumber) {
        case 0x40: return handleBasicArithmetic(cpu);
        case 0x41: return handleAdvancedMath(cpu);
        case 0x42: return handleTrigonometricFunction(cpu);
        case 0x43: return handleLogarithmFunction(cpu);
        case 0x44: return handleExponentialFunction(cpu);
        case 0x45: return handleSquareRoot(cpu);
        case 0x46: return handleRandomGeneration(cpu);
        case 0x47: return handleGreatestCommonDivisor(cpu);
        case 0x48: return handleLeastCommonMultiple(cpu);
        case 0x49: return handlePrimeCheck(cpu);
        case 0x4A: return handleFactorial(cpu);
        case 0x4B: return handleCombination(cpu);
        case 0x4C: return handlePermutation(cpu);
        case 0x4D: return handleAbsoluteValue(cpu);
        case 0x4E: return handleFindMaximum(cpu);
        case 0x4F: return handleFindMinimum(cpu);
        default:
            return createErrorResult(-1, QString("未实现的数学运算中断: 0x%1").arg(interruptNumber, 2, 16, QChar('0')));
    }
}

/**
 * @brief 获取支持的中断号范围
 * @return QPair<int, int> 中断号范围
 */
QPair<int, int> MathHandler::getSupportedInterruptRange() const
{
    return qMakePair(0x40, 0x4F);
}

/**
 * @brief 获取处理器描述
 * @return QString 描述信息
 */
QString MathHandler::getDescription() const
{
    return "数学运算处理器 - 支持基础和高级数学运算";
}

/**
 * @brief 重置处理器状态
 */
void MathHandler::reset()
{
    // 数学处理器通常不需要重置状态
    randomGenerator = QRandomGenerator::global();
}

/**
 * @brief INT 0x40 - 基础算术运算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleBasicArithmetic(CpuSimulator* cpu)
{
    int a = cpu->getRegister("AX");
    int b = cpu->getRegister("BX");
    int result = a + b;
    
    QMap<QString, int> resultMap;
    resultMap["AX"] = result;
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x41 - 高级数学运算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleAdvancedMath(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

/**
 * @brief INT 0x42 - 三角函数计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleTrigonometricFunction(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

/**
 * @brief INT 0x43 - 对数函数运算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleLogarithmFunction(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

/**
 * @brief INT 0x44 - 指数运算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleExponentialFunction(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

/**
 * @brief INT 0x45 - 平方根运算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleSquareRoot(CpuSimulator* cpu)
{
    int value = cpu->getRegister("AX");
    
    if (value < 0) {
        return createErrorResult(-1, "不能计算负数的平方根");
    }
    
    double result = qSqrt(static_cast<double>(value));
    
    QMap<QString, int> resultMap;
    resultMap["BX"] = doubleToFixedPoint(result);
    
    emit outputMessage(QString("平方根计算完成: √%1 = %2").arg(value).arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x46 - 随机数生成
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleRandomGeneration(CpuSimulator* cpu)
{
    int minValue = cpu->getRegister("AX");
    int maxValue = cpu->getRegister("BX");
    
    if (minValue > maxValue) {
        qSwap(minValue, maxValue);
    }
    
    int randomValue = randomGenerator->bounded(minValue, maxValue + 1);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = randomValue;
    
    emit outputMessage(QString("生成随机数: %1 (范围: %2-%3)").arg(randomValue).arg(minValue).arg(maxValue));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x45 - 最大公约数计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleGreatestCommonDivisor(CpuSimulator* cpu)
{
    int a = cpu->getRegister("AX");
    int b = cpu->getRegister("BX");
    
    int gcd = calculateGcd(qAbs(a), qAbs(b));
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = gcd;
    
    emit outputMessage(QString("最大公约数计算完成: GCD(%1, %2) = %3").arg(a).arg(b).arg(gcd));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x46 - 最小公倍数计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleLeastCommonMultiple(CpuSimulator* cpu)
{
    int a = cpu->getRegister("AX");
    int b = cpu->getRegister("BX");
    
    int lcm = calculateLcm(a, b);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = lcm;
    
    emit outputMessage(QString("最小公倍数计算完成: LCM(%1, %2) = %3").arg(a).arg(b).arg(lcm));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x47 - 质数判断
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handlePrimeCheck(CpuSimulator* cpu)
{
    int number = cpu->getRegister("AX");
    
    bool isPrimeNumber = isPrime(number);
    
    QMap<QString, int> resultMap;
    resultMap["BX"] = isPrimeNumber ? 1 : 0;
    
    emit outputMessage(QString("质数判断完成: %1 %2质数").arg(number).arg(isPrimeNumber ? "是" : "不是"));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x48 - 阶乘计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleFactorial(CpuSimulator* cpu)
{
    int number = cpu->getRegister("AX");
    
    qint64 result = calculateFactorial(number);
    
    QMap<QString, int> resultMap;
    resultMap["BX"] = result;
    
    emit outputMessage(QString("阶乘计算完成: %1! = %2").arg(number).arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x49 - 组合计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleCombination(CpuSimulator* cpu)
{
    int n = cpu->getRegister("AX");
    int r = cpu->getRegister("BX");
    
    qint64 result = calculateCombination(n, r);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = result;
    
    emit outputMessage(QString("组合计算完成: C(%1, %2) = %3").arg(n).arg(r).arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x4A - 排列计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handlePermutation(CpuSimulator* cpu)
{
    int n = cpu->getRegister("AX");
    int r = cpu->getRegister("BX");
    
    qint64 result = calculatePermutation(n, r);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = result;
    
    emit outputMessage(QString("排列计算完成: P(%1, %2) = %3").arg(n).arg(r).arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x4B - 绝对值计算
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleAbsoluteValue(CpuSimulator* cpu)
{
    int value = cpu->getRegister("AX");
    
    int result = qAbs(value);
    
    QMap<QString, int> resultMap;
    resultMap["AX"] = result;
    
    emit outputMessage(QString("绝对值计算完成: |%1| = %2").arg(value).arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x4C - 数组最大值
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleFindMaximum(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

/**
 * @brief INT 0x4D - 数组最小值
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult MathHandler::handleFindMinimum(CpuSimulator* cpu)
{
    Q_UNUSED(cpu)
    return createSuccessResult();
}

// 辅助数学函数实现

/**
 * @brief 计算最大公约数（欧几里得算法）
 * @param a 数值1
 * @param b 数值2
 * @return int 最大公约数
 */
int MathHandler::calculateGcd(int a, int b)
{
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

/**
 * @brief 判断是否为质数
 * @param n 待判断数值
 * @return bool 是否为质数
 */
bool MathHandler::isPrime(int n)
{
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    
    return true;
}

/**
 * @brief 计算最小公倍数
 * @param a 数值1
 * @param b 数值2
 * @return int 最小公倍数
 */
int MathHandler::calculateLcm(int a, int b)
{
    return (a * b) / calculateGcd(a, b);
}

/**
 * @brief 计算阶乘
 * @param n 待计算阶乘的数值
 * @return qint64 阶乘结果
 */
qint64 MathHandler::calculateFactorial(int n)
{
    if (n <= 1) return 1;
    return n * calculateFactorial(n - 1);
}

/**
 * @brief 计算组合数
 * @param n 总数
 * @param r 选择数
 * @return qint64 组合数
 */
qint64 MathHandler::calculateCombination(int n, int r)
{
    if (r > n) return 0;
    if (r == 0 || r == n) return 1;
    return calculateFactorial(n) / (calculateFactorial(r) * calculateFactorial(n - r));
}

/**
 * @brief 计算排列数
 * @param n 总数
 * @param r 选择数
 * @return qint64 排列数
 */
qint64 MathHandler::calculatePermutation(int n, int r)
{
    if (r > n) return 0;
    return calculateFactorial(n) / calculateFactorial(n - r);
}

/**
 * @brief 将浮点数转换为定点数（放大1000倍）
 * @param value 浮点数
 * @return int 定点数
 */
int MathHandler::doubleToFixedPoint(double value)
{
    return static_cast<int>(value * FIXED_POINT_SCALE);
}

/**
 * @brief 将定点数转换为浮点数（缩小1000倍）
 * @param fixedPoint 定点数
 * @return double 浮点数
 */
double MathHandler::fixedPointToDouble(int fixedPoint)
{
    return static_cast<double>(fixedPoint) / FIXED_POINT_SCALE;
}

// 占位实现其他方法
//SystemCallResult MathHandler::handleExponentialFunction(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
QList<int> MathHandler::readIntArrayFromMemory(CpuSimulator* cpu, int address, int length) { Q_UNUSED(cpu) Q_UNUSED(address) Q_UNUSED(length) return {}; }
bool MathHandler::validateMathParameters(const QString& operation, const QList<int>& params) { Q_UNUSED(operation) Q_UNUSED(params) return true; } 
